package com.xfmax.sharesdk.impl;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xfmax.sharesdk.base.IResult;
import com.xfmax.sharesdk.base.IShareable;
import com.xfmax.sharesdk.base.OnCallback;
import com.xfmax.sharesdk.config.Platform;
import com.xfmax.sharesdk.config.ResultCode;
import com.xfmax.sharesdk.config.ShareTo;
import com.xfmax.sharesdk.model.IMediaObject;
import com.xfmax.sharesdk.model.MoImage;
import com.xfmax.sharesdk.model.MoMusic;
import com.xfmax.sharesdk.model.MoVideo;
import com.xfmax.sharesdk.model.MoWeb;
import com.xfmax.sharesdk.model.ShareData;

import java.util.WeakHashMap;


/**
 * Created by base on 18/2/2.
 */

public class WXShare implements IResult, IWXAPIEventHandler, IShareable {
    private static final String TAG = WXShare.class.getSimpleName();

    public static int REQUEST_CODE = 1999;

    static WeakHashMap<IResult, Boolean> services = new WeakHashMap<>();

    final protected Activity mActivity;
    final protected Platform mPlatform;
    protected OnCallback mCallback;
    IWXAPI mApi;

    protected WXShare(Activity activity, Platform platform) {
        mActivity = activity;
        mPlatform = platform;
        if (!TextUtils.isEmpty(platform.getAppId())) {
            mApi = WXAPIFactory.createWXAPI(activity.getApplicationContext(), platform.getAppId(), true);
            mApi.registerApp(platform.getAppId());
        }
        services.put(this, true);
    }

    @Override
    public void Share(ShareData data, OnCallback<String> callback) {
        if (!mApi.isWXAppInstalled()) {
            callback.onFailed(mActivity,ResultCode.RESULT_FAILED,"您没有安装微信！");
        }

        BaseReq req = makeReq(data);
        mApi.sendReq(req);
    }

    BaseReq makeReq(ShareData data) {
        WXMediaMessage message = new WXMediaMessage();
        if (data.hasTitle()) {
            message.title = data.title;
        }
        if (data.hasDescription()) {
            message.description = data.description;
        }
        if (data.hasThumb()) {
            message.thumbData = data.thumb.toBytes();
        }

        switch (data.type()) {
            case IMediaObject.TYPE_TEXT:
                message.mediaObject = new WXTextObject(data.text);
                break;
            case IMediaObject.TYPE_WEB:
                message.mediaObject = new WXWebpageObject(((MoWeb) data.media).url);
                break;
            case IMediaObject.TYPE_EMOJI:
            case IMediaObject.TYPE_IMAGE: {
                MoImage mo = (MoImage) data.media;
                WXImageObject wxo = new WXImageObject();
                wxo.imagePath = mo.toUri();
                if (TextUtils.isEmpty(wxo.imagePath)) {
                    wxo.imageData = mo.toBytes();
                }
                message.mediaObject = wxo;
            }
            break;
            case IMediaObject.TYPE_VIDEO: {
                MoVideo mo = (MoVideo) data.media;
                WXVideoObject wxo = new WXVideoObject();
                wxo.videoUrl = mo.mediaUrl;
                wxo.videoLowBandUrl = mo.lowBandUrl;
                message.mediaObject = wxo;
            }
            break;
            case IMediaObject.TYPE_MUSIC: {
                MoMusic mo = (MoMusic) data.media;
                WXMusicObject wxo = new WXMusicObject();
                wxo.musicUrl = mo.mediaUrl;
                wxo.musicDataUrl = mo.mediaDataUrl;
                wxo.musicLowBandUrl = mo.lowBandUrl;
                wxo.musicLowBandDataUrl = mo.lowBandDataUrl;
                message.mediaObject = wxo;
            }
            break;

        }

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = message;
        req.scene = toScene(mPlatform.getName());

        return req;
    }


    int toScene(String platform) {
        switch (platform) {
            case ShareTo.WXSession:
                return 0;
            case ShareTo.WXTimeline:
                return 1;
            case ShareTo.WXFavorite:
                return 2;
        }
        return 0;
    }

    /**
     * 微信向第三方发送请求的时候被调用
     *
     * @param baseReq
     */
    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        Log.e(TAG, "transaction = " + resp.transaction + ", type = " + resp.getType() + ", errCode = " + resp.errCode + ", err = " + resp.errStr);

        if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
            switch (resp.getType()) {
                case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                    onResultOk((SendMessageToWX.Resp) resp);
                    break;
            }
        } else if (resp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
            mCallback.onFailed(mActivity, ResultCode.RESULT_CANCELLED, toMessage(resp));
        } else {
            mCallback.onFailed(mActivity, ResultCode.RESULT_FAILED, toMessage(resp));
        }
        mCallback.onCompleted(mActivity);
    }

    private String toMessage(BaseResp resp) {
        return "[" + resp.errCode + "]" + (resp.errStr == null ? "" : resp.errStr);
    }

    @Override
    public void onResult() {

    }

    protected void onResultOk(SendMessageToWX.Resp resp) {

    }



}
